//
//  UPYinDaoPageViewController.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/15.
//

#import "UPYinDaoPageViewController.h"
#import "UPTabBarViewController.h"
#import "UPMineInfo.h"
#import "UPLoginViewController.h"
#import "UPTabBarViewController.h"

@interface UPYinDaoPageViewController ()
@property (nonatomic, strong) UIButton *retryButton;
@end

@implementation UPYinDaoPageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.view addSubview: self.retryButton];
    [self.retryButton mas_makeConstraints:^(MASConstraintMaker *make) {
            
        make.leading.trailing.equalTo(self.retryButton.superview).inset(16);
        make.height.mas_equalTo(45.0);
        make.bottom.equalTo(self.retryButton.superview).offset(-46);
    }];
    
    [self fetchDataSources];
}

- (UIButton *)retryButton {
    if (!_retryButton) {
        _retryButton = [UIButton buttonWithType: UIButtonTypeSystem];
        [_retryButton setTitle: LocalizableForKey(@"retry again") forState:UIControlStateNormal];
        [_retryButton addTarget:self
                     action:@selector(buttonTapped:)
           forControlEvents:UIControlEventTouchUpInside];
        _retryButton.layer.masksToBounds = YES;
        _retryButton.layer.cornerRadius = 22.5;
        _retryButton.backgroundColor = [UIColor colorWithHexString:@"#000000"];
        [_retryButton setTitleColor: [UIColor colorWithHexString:@"#FFFFFF"] forState: UIControlStateNormal];
        [_retryButton setHidden:YES];
        [self.view addSubview:_retryButton];
    }
    return _retryButton;
}

- (void)fetchDataSources {
    [UPProgressHUD show];
    __block typeof(self) weakSelf = self;
    [UPStocksAPIManager fetchEnvironmentWithCompletion:^(UPYinDaoModel * _Nullable yinDaoModel, NSString * _Nullable msg) {
        if (yinDaoModel != nil) {
            [weakSelf.retryButton setHidden:YES];
            [UPProgressHUD dismiss];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf updateRootViewContoller];
            });
        } else {
            [weakSelf.retryButton setHidden:NO];
//            [UPProgressHUD showInfoWithStatus:msg];
            [UPProgressHUD dismiss];
        }
    }];
}

- (void)buttonTapped: (UIButton *)sender {
    [self fetchDataSources];
}

- (void)updateRootViewContoller {
    // 1. 安全获取window
    UIWindow *window = [UIApplication up_currentKeyWindow];
    // 2. 安全获取登录状态
    UPMineInfo *mineInfo = [UPMineInfo sharedManager];
    if (!mineInfo) {
        NSLog(@"UPMineInfo sharedManager is nil");
        return;
    }
    
    BOOL needLogin = !mineInfo.isLogin;
    UIViewController *currentRootVC = window.rootViewController;
    
    // 3. 检查是否需要更新rootViewController
    BOOL topIsLoginVC = [currentRootVC isKindOfClass:[UPLoginViewController class]];
    BOOL topIsTabVC = [currentRootVC isKindOfClass:[UPTabBarViewController class]];
    
    if ((needLogin && topIsLoginVC) || (!needLogin && topIsTabVC)) {
        return; // 已经是正确的rootVC，不需要更新
    }
    
    // 4. 创建新的rootViewController
    UIViewController *rootVC = nil;
    if (mineInfo.isLogin) {
        rootVC = [[UPTabBarViewController alloc] init];
    } else {
        rootVC = [[UPLoginViewController alloc] init];
    }
    
    if (!rootVC) {
        NSLog(@"Failed to create root view controller");
        return;
    }
    
    // 5. 安全切换rootViewController（添加动画过渡）
    [UIView transitionWithView:window
                      duration:0.3
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:^{
                        window.rootViewController = rootVC;
                    }
                    completion:nil];
    
    [window makeKeyAndVisible];
}
@end
